package utility

import (
	"strconv"
	"strings"
	"time"
)

// dateFormatToGoFormat 将 PHP 风格的日期格式转换为 Go 语言的日期格式
func dateFormatToGoFormat(format string) string {
	replacements := map[string]string{
		"Y": "2006",
		"m": "01",
		"d": "02",
		"H": "15",
		"i": "04",
		"s": "05",
	}

	for phpToken, goToken := range replacements {
		format = strings.ReplaceAll(format, phpToken, goToken)
	}

	return format
}

// FormatTimestamp 将时间戳转换为指定格式的日期字符串
func FormatTimestamp(timestamp string, format string) string {
	if timestamp == "" {
		return ""
	}
	// 如果格式为空字符串，默认使用 "Y-m-d H:i:s"
	if format == "" {
		format = "Y-m-d H:i:s"
	}
	ts, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil {
		return ""
	}
	goFormat := dateFormatToGoFormat(format)
	return time.Unix(ts, 0).Format(goFormat)
}
